package cn.edu.jlu.grid.vjm;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class VJobMessageProcessor implements Runnable {
	private Socket connection = null;
	private VJMMessage msg = null;
	
	public VJobMessageProcessor(VJMMessage msg) {
		this.msg = msg;
	}
	public VJobMessageProcessor(Socket connection) {
		this.connection = connection;
	}
	
	public void run() {
		if(connection == null) {
			/* send message to vjm center */
			VJobExecute ve = VJobExecute.getInstance();
			Socket socket = null;
			msg.onSend();
			try {
				socket = new Socket(ve.getVJCAddress(), ve.getVJCPort());
				ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream());
				os.writeObject(msg);
				System.out.println("send message " + msg);
				os.flush();
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {socket.close();} catch(Exception e) {}
			}
		} else {
			/* read message from vjm center */
			try {
				ObjectInputStream oin = new ObjectInputStream(connection.getInputStream());
				Object obj = oin.readObject();
				if(obj instanceof VJMMessage) {
					System.out.println("Receiving Message: " + obj);
					((VJMMessage) obj).onReceive(connection);
				} else {
					// exception
					System.out.println("Receiving unkown message");
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(connection != null) {
			try { connection.close(); } catch(Exception e) {}
		}
	}
}
